package com.leetcode;

import com.leetcode.common.TreeNode;

import java.util.*;

/**
 * 103. 二叉树的锯齿形层序遍历
 * 通过队列的存取值方向改变顺序
 *
 * @author fy
 * @date 2022/4/14 20:37
 */
public class Solution103_1 {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean orderLeft = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            Deque<Integer> levels = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (orderLeft) {
                    levels.offerLast(node.val);
                } else {
                    levels.offerFirst(node.val);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            orderLeft = !orderLeft;
            res.add(new LinkedList<>(levels));
        }
        return res;
    }

}
